# -*- coding:UTF-8 -*-
import random
import time
import traceback

from db import *
from spider_xue.ip import headers_list
from spider_xue.logger import logging
from spider_xue.settings import FIFTEEN, FIVE, INFO, NINE_TIME_STAMP, URL1, Vol, ERROR, ding_url2, ding_url1, ding_url0, ding_urlyes, ding_urlban
from spider_xue.spider import Snowball
from spider_xue.utils import send_s_msg


def do_together_one_mintue(account, stocks, workQueueIP):
    # snow = Snowball(son_work_together)
    snow = Snowball(son_work_together_one_mintue)
    # flag, iipp = snow.refresh_session_queue(account['cookies'], workQueueIP)
    iipp = workQueueIP.get()
    snow.headers['user-agent'] = random.choice(headers_list)
    snow.headers['cookie'] = account['cookies']
    snow.session.headers = snow.headers
    snow.session.proxies = {"http": "http://{}".format(iipp["ip"])}

    fail = []

    tt = int(time.time())
    start = str(tt + 3600) + "000"
    end = '300'
    nine = settings_db.find_one({"name": 'nine_timestamp'})
    for i in range(len(stocks)):
        try:
            flag = snow.get_res_together_no_save(
                URL1, stocks[i], start, end, data_one_db, nine['timestamp'])
            # flag = snow.get_res_together(stocks[i]['symbol'], start, end)
            if not flag:
                fail.append(stocks[i])
            time.sleep(0.1)
        except Exception as e:
            if 'HTTPConnectionPool' not in str(e):
                traceback.print_exc()
            err = str(e) if 'HTTPConnectionPool' not in str(
                e) else "HTTPConnectionPool problem"
            # logging.error(
            #     f"mission Exception {stocks[i]['symbol']} {err} --- use IP: {iipp['ip']} ")
            # new_ip_obj.delete_one(iipp)
            return fail + stocks[i:], iipp['ip']
    return fail, iipp['ip']


def son_work_together_one_mintue(x, stock, timestamp):
    symbol = x['symbol']
    item = x['item']

    end_price = stock['end_price']

    lol = (item[-1][5] - end_price) / end_price * 100
    if lol < -5:
        return
    elif lol > 8:
        # if lol > 9.85:
        #     return
        # else:
        #     send_s_msg(stock, f"{str(lol)}快要板了，抓紧时间买入!!!!!!!!!!!!!!!!!{str(item[-1][5])}", ding_urlban)
        return 

    five_max_0 = stock['p5']
    
    yes = stock.get("yesterday")
    byes = stock.get("byesterday")

    r = len(item)
    msg_list = []
    msg_list2 = []

    flag = False
    flag2 = False
    liang = 0
    first_index = 0

    for end_index in range(r-1, 0, -1):
        ts = int(item[end_index][0] / 1000)
        if ts == timestamp + 60:
            first_index = end_index
            break
        liang += item[end_index][9]
    
    lolx = (item[first_index][2] - end_price) / end_price * 100
    if lolx < -5:
        return
    lolx = (item[-1][5] - item[first_index][2]) / item[first_index][2] * 100
    if lolx < -3:
        return

    for end_index in range(r-1, r-3, -1):
        ts = int(item[end_index][0] / 1000)
        if ts % 120 != 0:
            continue
        if ts < timestamp + 120:
            break
        if ts < timestamp + 300:
            head_index = end_index - 3 + int((ts - timestamp) / 60)
        else:
            head_index = end_index - 4
        tmp5 = 0
        if item[end_index][5] - item[head_index][2] <= 0:
            continue
        for x in range(head_index, end_index+1):
            tmp5 += item[x][9]
        
        b_liang = round(liang / stock.get('liang'), 2) if stock.get('liang') else 0
        
        p = round(tmp5 / five_max_0, 2)
        if p >= 2:
            if end_index + 2 >= r:
                flag = True
            asve = {"p5": p, 'price': item[end_index][5], 'liang': liang, 'range': round(lol, 2), 'ts': ts}
 
            if record_main_db.find_one({"symbol": symbol, 'ts': timestamp-34200}):
                record_main_db.update_one({"symbol": symbol, 'ts': timestamp-34200}, {"$push": {"sons": asve}, "$set": {'update_time': ts}})
            else:
                record_main_db.update_one({"symbol": symbol, 'ts': timestamp-34200}, 
                {"$set": {'ts': timestamp-34200,'macd': stock.get('macd', 0), 'update_time': ts,
                'high': stock.get('today', 0), 'sons': [asve]}}, upsert=True)
            
            msg_list.append(f"{time.strftime('%d-%H:%M', time.localtime(ts))}#{stock.get('use', -1)}#{p}倍#{round(lol, 2)}%#{item[end_index][5]}￥#{b_liang}倍")
        p2 = 0 
        if yes:
            # 昨天出现
            p2 = round(tmp5 / five_max_0, 2)
        elif byes:
            # 前天出现 但是昨天没有出现
            p2 = round(tmp5 / five_max_0, 2)

        if p2 and p2 >= 1.5:
            if end_index + 2 >= r:
                flag2 = True     
            asve = {"p5": p2, 'price': item[end_index][5], 'liang': liang, 'range': round(lol, 2), 'ts': ts}
            if record_yes_main_db.find_one({"symbol": symbol, 'ts': timestamp-34200}):
                record_yes_main_db.update_one({"symbol": symbol, 'ts': timestamp-34200}, {"$push": {"sons": asve}, "$set": {'update_time': ts}})
            else:
                record_yes_main_db.update_one({"symbol": symbol, 'ts': timestamp-34200}, 
                {"$set": {'ts': timestamp-34200,'macd': stock.get('macd', 0), 'update_time': ts,
                'high': stock.get('today', 0), 'sons': [asve]}}, upsert=True)
            msg_list2.append(f"{time.strftime('%d-%H:%M', time.localtime(ts))}#{p}倍#{round(lol, 2)}%#{item[end_index][5]}￥#{b_liang}倍")

    if flag and msg_list:
        # msg_list = query_find = record_db.find({"symbol": symbol, "ts": {"$gte": NINE_TIME_STAMPi}})
        msg = ''
        for i in msg_list:
            # msg = msg + "- " + f"{time.strftime('%H:%M', time.localtime(i['ts']))}#{i['p']}#{i['type']}" + '\n'
            msg = msg + "- " + i + '\n'
       
        dates = record_day_db.find({"symbol": symbol})
        dates_msg = [x['date'] for x in dates]
        dates_msg = ' '.join(dates_msg)
        if stock.get('today') >= 3:
            send_s_msg(stock, msg, ding_url2, dates_msg)
        elif stock.get('today') == 2:
            send_s_msg(stock, msg, ding_url1, dates_msg)
        else:
            send_s_msg(stock, msg, ding_url0, dates_msg)
    
    if flag2 and msg_list2:
        msg = ''
        for i in msg_list:
            # msg = msg + "- " + f"{time.strftime('%H:%M', time.localtime(i['ts']))}#{i['p']}#{i['type']}" + '\n'
            msg = msg + "- " + i + '\n'
       
        dates = record_day_db.find({"symbol": symbol})
        dates_msg = [x['date'] for x in dates]
        dates_msg = ' '.join(dates_msg)
        send_s_msg(stock, msg, ding_urlyes, dates_msg)
           


def fix_one_mintue(account, stocks, workQueueIP):
    snow = Snowball(fix_work)
    iipp = workQueueIP.get()
    snow.headers['user-agent'] = random.choice(headers_list)
    snow.headers['cookie'] = account['cookies']
    snow.session.headers = snow.headers
    snow.session.proxies = {"http": "http://{}".format(iipp["ip"])}

    fail = []

    tt = int(time.time())
    start = str(tt + 3600) + "000"
    end = '300'
    nine = settings_db.find_one({"name": 'nine_timestamp'})
    for i in range(len(stocks)):
        try:
            flag = snow.get_res_together_no_save(
                URL1, stocks[i], start, end, data_one_db, nine['timestamp'])
            # flag = snow.get_res_together(stocks[i]['symbol'], start, end)
            if not flag:
                fail.append(stocks[i])
            time.sleep(0.2)
        except Exception as e:
            if 'HTTPConnectionPool' not in str(e):
                traceback.print_exc()
            err = str(e) if 'HTTPConnectionPool' not in str(
                e) else "HTTPConnectionPool problem"
            logging.error(
                f"mission Exception {stocks[i]['symbol']} {err} --- use IP: {iipp['ip']} ")
            # new_ip_obj.delete_one(iipp)
            return fail + stocks[i:], iipp['ip']
    return fail, iipp['ip']


def fix_work(x, stock, timestamp):
    symbol = x['symbol']
    item = x['item']
    history = history_five_db.find_one({"symbol": symbol})

    end_price = stock['end_price']

    lol = (item[-1][5] - end_price) / end_price * 100
    if lol < -6:
        return
    five_max_0 = stock['p5']
    # xxx = timestamp - 3600 * 24 - 9 * 3600 - 1800
    # five_max_0 = history['five_time_dict'][time.strftime('%Y-%m-%d', time.localtime(xxx))]
    
    yes = stock.get("yesterday")
    byes = stock.get("byesterday")
    r = len(item)

    liang = 0
    lol_start = 0

    ll = []
    ll2 = []

    for end_index in range(0, r):

        ts = int(item[end_index][0] / 1000)

        if timestamp <= ts:
            liang += item[end_index][9]
        if timestamp + 60 == ts:
            lol_start = item[end_index][2]
            lol = (lol_start - end_price) / end_price * 100
            if lol < -4:
                return 

        if ts < timestamp + 120:
            continue

        if ts % 120 != 0:
            continue
        
        if ts < timestamp + 300:
            head_index = end_index - 3 + int((ts - timestamp) / 60)
        else:
            head_index = end_index - 4
        tmp5 = 0
        if item[end_index][5] - item[head_index][2] <= 0:
            continue
        for x in range(head_index, end_index+1):
            tmp5 += item[x][9]
        p = round(tmp5 / five_max_0, 2)

        if p >= 2:
            lol = (item[end_index][5] - lol_start) / lol_start * 100
            if lol < -3:
                return
            # if record_main_db.find_one({"symbol": symbol, 'ts': timestamp-34200}):
            #     record_main_db.update_one({"symbol": symbol, 'ts': timestamp-34200}, {"$push": {"sons": asve}, "$set": {'update_time': ts}})
            # else:
            #     record_main_db.update_one({"symbol": symbol, 'ts': timestamp-34200}, 
            #     {"$set": {'ts': timestamp-34200,'macd': stock.get('macd', 0), 'update_time': ts,
            #     'high': stock.get('high', 0), 'sons': [asve]}}, upsert=True)
            ll.append({"symbol": symbol, 'ts': timestamp-34200,'macd': stock.get('macd', 0), 'update_time': ts, 'high': stock.get('today', 0), 
                "p5": p, 'price': item[end_index][5], 'liang': liang, 'range': round(lol, 2)})

        p2 = 0
        if yes:
            # 昨天出现
            p2 = round(tmp5 / five_max_0, 2)
        elif byes:
            # 前天出现 但是昨天没有出现
            p2 = round(tmp5 / five_max_0, 2)

        if p2 and p2 >= 1.5:
            lolx = (item[end_index][5] - lol_start) / lol_start * 100
            if lolx < -3:
                return
            # asve["p5"] = p2
            # if record_yes_main_db.find_one({"symbol": symbol, 'ts': timestamp-34200}):
            #     record_yes_main_db.update_one({"symbol": symbol, 'ts': timestamp-34200}, {"$push": {"sons": asve}, "$set": {'update_time': ts}})
            # else:
            #     record_yes_main_db.update_one({"symbol": symbol, 'ts': timestamp-34200}, 
            #     {"$set": {'ts': timestamp-34200,'macd': stock.get('macd', 0), 'update_time': ts,
            #     'high': stock.get('high', 0), 'sons': [asve]}}, upsert=True)
            ll2.append({"symbol": symbol, 'ts': timestamp-34200,'macd': stock.get('macd', 0), 'update_time': ts, 'high': stock.get('today', 0), 
                "p5": p2, 'price': item[end_index][5], 'liang': liang, 'range': round(lol, 2)})

    if ll:
        opopd = {"symbol": ll[-1]['symbol'], 'ts': ll[-1]['ts'], 'macd': ll[-1]['macd'], 'update_time': ll[-1]['update_time'], 'high': ll[-1]['high'], 'sons': []}
        for npp in ll:
            npp['ts'] = npp['update_time']
            opopd['sons'].append(npp)
        record_main_db.delete_many({"symbol": opopd['symbol'], 'ts': opopd['ts']})
        record_main_db.update_one({"symbol": opopd['symbol'], 'ts': opopd['ts']}, {"$set": opopd}, upsert=True)
    
    if ll2:
        opopd = {"symbol": ll2[-1]['symbol'], 'ts': ll2[-1]['ts'], 'macd': ll2[-1]['macd'], 'update_time': ll2[-1]['update_time'], 'high': ll2[-1]['high'], 'sons': []}
        for npp in ll2:
            npp['ts'] = npp['update_time']
            opopd['sons'].append(npp)
        record_yes_main_db.delete_many({"symbol": opopd['symbol'], 'ts': opopd['ts']})
        record_yes_main_db.update_one({"symbol": opopd['symbol'], 'ts': opopd['ts']}, {"$set": opopd}, upsert=True)
